﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.IO;

using KaoQin.BLL;
using KaoQin.Common;
using KaoQin.Model;
using KaoQin.RFIDLIB;
using AForge.Video.DirectShow;
using AForge.Video;
using System.Drawing;
using System.Drawing.Imaging;

namespace KaoQin.WPFApp.personnel
{
    /// <summary>
    /// EmployeeMgr.xaml 的交互逻辑
    /// </summary>
    public partial class EmployeeMgr : Window
    {
        public EmployeeMgr()
        {
            InitializeComponent();
        }

        private FilterInfoCollection videoDevices;
        private VideoCaptureDevice videoDevice;

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.initData();
            this.initWebcam();
        }

        private void initData()
        {
            try
            {
                this.bindList();
                cbSex.ItemsSource = StaticDataHelper.GetSexData();
                
                
            }
            catch (Exception ex)
            {
                Logger.Write("绑定员工列表失败：" + ex.Message);
                MessageBox.Show("绑定员工列表失败：" + ex.Message);
            }
        }

        private void bindList()
        {
            lstEmployee.ItemsSource = new Employee().GetModelList("KName like '%"+txtKey.Text.Trim()+"%' order by CreateTime desc");
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            bindList();
        }

        private void lstEmployee_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EmployeeInfo model = (EmployeeInfo)gridempInfo.DataContext;
                model.ID = Guid.NewGuid().ToString();
                model.CreateTime = DateTime.Now;
                model.PhotoUrl = txtUrl.Text;
                model.ICCardID = string.Empty;

                if (string.IsNullOrEmpty(model.WordNum))
                {
                    MessageBox.Show("员工工号不能为空");
                    return;
                }
                if (string.IsNullOrEmpty(model.KName))
                {
                    MessageBox.Show("员工姓名不能为空");
                    return;
                }

                if (new Employee().Exists(model.ID, model.WordNum.ToLower()))
                {
                    MessageBox.Show("此工号已存在");
                    return;
                }

                model.WordNum = model.WordNum.ToLower();

                
                
                new Employee().Add(model);
                MessageBox.Show("新增成功");
                bindList();
            }
            catch (Exception ex)
            {
                Logger.Write("新增失败：" + ex.Message);
                MessageBox.Show("新增失败:" + ex.Message);
            }
        }

        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                EmployeeInfo model = (EmployeeInfo)gridempInfo.DataContext;
                model.PhotoUrl = txtUrl.Text;

                if (string.IsNullOrEmpty(model.WordNum))
                {
                    MessageBox.Show("员工工号不能为空");
                    return;
                }
                if (string.IsNullOrEmpty(model.KName))
                {
                    MessageBox.Show("员工姓名不能为空");
                    return;
                }

                if (new Employee().Exists(model.ID, model.WordNum.ToLower()))
                {
                    MessageBox.Show("此工号已存在");
                    return;
                }
                model.WordNum = model.WordNum.ToLower();
                new Employee().Update(model);
                MessageBox.Show("修改成功"); 
            }
            catch (Exception ex)
            {
                Logger.Write("修改失败：" + ex.Message);
                MessageBox.Show("修改失败:" + ex.Message);
            }
        }

        

        private void btnUploadPic_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog open = new OpenFileDialog();
                
                open.Title = "选择照片";
                open.Filter = "jpg文件（.jpeg）|*.jpg|所有文件|*.*";//文件扩展名
                
                if (open.ShowDialog().Value)
                {
                    string filePath= "\\Photos\\Init";
                    string fileName = Guid.NewGuid().ToString() + System.IO.Path.GetExtension(open.FileName);
                    if (FileHelper.CopyFile(open.FileName, FileHelper.GetcurrPath() + "\\" + filePath,fileName))
                    {

                        txtUrl.Text = filePath + "\\" + fileName;;

                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Write("选择照片失败：" + ex.Message);
                MessageBox.Show("选择照片失败:" + ex.Message);
            }
        }

        

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Disconnect();
            this.Close();
        }

        private void cbCam_Checked(object sender, RoutedEventArgs e)
        {
            this.Connect();
            gridCam.Visibility = Visibility.Visible;
            btnCam.IsEnabled = true;
        }

        private void cbCam_Unchecked(object sender, RoutedEventArgs e)
        {
            this.Disconnect();
            gridCam.Visibility = Visibility.Collapsed; ;
        }

        private void Disconnect()
        {
            if (webcamPlayer.VideoSource != null)
            {
                // stop video device
                webcamPlayer.SignalToStop();
                webcamPlayer.WaitForStop();
                webcamPlayer.VideoSource = null;
            }
        }

        private void Connect()
        {
            if (videoDevice != null)
            {
                
                webcamPlayer.VideoSource = videoDevice;
                webcamPlayer.Start();
                

            }
        }

        private void videoDevice_SnapshotFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap img = (Bitmap)eventArgs.Frame.Clone();
            this.SaveImg(img);
        }

        private bool SaveImg(Bitmap img)
        {
            bool flag = false;
            string fileName;
            string filePath;
            try
            {
                filePath = "\\Photos\\Init";
                FileHelper.CreateDirectory( FileHelper.GetcurrPath() +"\\"+filePath);
                fileName = @"\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                img.Save(FileHelper.GetcurrPath() + "\\" + filePath + "\\" + fileName, ImageFormat.Jpeg);
                this.txtUrl.Dispatcher.Invoke(new Action(() => {
                    this.txtUrl.Text = filePath + "\\" + fileName;;
                }));  
                flag = true;
            }

            catch (Exception ex)
            {
                Logger.Write("保存照片失败：" + ex.Message);
                MessageBox.Show("保存照片失败:" + ex.Message);
            }

            return flag;
        }

        private void initWebcam()
        {
            SysWebcamParasInfo webcamParas = new SysWebcamParas().GetModel("48165275-EE69-4E01-A232-7BD4A9E28D4F");

            if (webcamParas != null)
            {
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                if (videoDevices.Count != 0)
                {
                    videoDevice = new VideoCaptureDevice(webcamParas.value);
                    if (videoDevice != null)
                    {
                        videoDevice.ProvideSnapshots = true;
                        videoDevice.SnapshotFrame += new NewFrameEventHandler(videoDevice_SnapshotFrame);
                        
                    }
                    else
                    {
                        MessageBox.Show("请先进行视频设备设置");
                    }
                    
                }


            }
        }

        private void btnCam_Click(object sender, RoutedEventArgs e)
        {
            
            videoDevice.SimulateTrigger();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Disconnect();
        }

        



       
    }
}
